package cn.asura.controller;

import cn.asura.pojo.DateAndView;
import cn.asura.pojo.User;
import cn.asura.service.BlogViewsService;
import cn.asura.service.UserService;
import cn.asura.utils.FileUpLoadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

/**
 * home 控制器
 * @author chen
 */
@Controller
@RequestMapping("/home")
public class HomeController {

    private UserService userService;
    private BlogViewsService blogViewsService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setBlogViewsService(BlogViewsService blogViewsService) {
        this.blogViewsService = blogViewsService;
    }

    /**
     * 跳转到登录页面
     * @return login 页面
     */
    @RequestMapping("/index")
    public String index() {
        return "view/index";
    }

    @GetMapping("/login")
    public String jumpToLogin() {
        return "login";
    }

    /**
     * 登录请求，根据 email 和 pwd 登录，并把信息存进 session 域中
     * @param session session
     * @param email 帐号
     * @param pwd 密码
     * @return admin.jsp
     */
    @PostMapping("/login")
    public ModelAndView login(String email, String pwd, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.getUserByEmailAndPwd(email, pwd);
        if (user != null) {
            session.setAttribute("_USER_IMG", user.getAvatar());
            session.setAttribute("_USER_MODEL", user);
            session.setAttribute("_USER_EMAIL", user.getEmail());
            modelAndView.setViewName("forward:/home/admin.do");
        } else {
            modelAndView.setViewName("login");
            modelAndView.addObject("message", "请检查用户名和密码");
        }
        return modelAndView;
    }

    /**
     * 注销登录，清空 session 中的信息并跳转到登录页面
     * @param session session
     * @return login.jsp
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }

    /**
     * 跳转到注册页面
     * @return regist.jsp
     */
    @GetMapping("/regist")
    public String jumpToRegist() {
        return "regist";
    }

    /**
     * 注册，添加 user 到数据库中
     * @param email email
     * @param pwd pwd
     * @return 登录页面
     */
    @PostMapping("/regist")
    public ModelAndView regist(String email, String pwd) {
        ModelAndView modelAndView = new ModelAndView();
        HashMap<String, Object> map = new HashMap<>(512);
        map.put("email", email);
        map.put("pwd", pwd);
        int rowNum = userService.addUser(map);
        modelAndView.setViewName("login");
        if (rowNum > 0) {
            modelAndView.addObject("message", "注册成功,欢迎使用!");
        } else {
            modelAndView.addObject("message", "请检查用户名和密码");
        }
        return modelAndView;
    }

    /**
     * 更新信息 -- GET
     * @return info.jsp
     */
    @GetMapping("/updateInfo")
    public String jumpToUpdateInfo(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("_USER_MODEL");
        req.setAttribute("user", user);
        return "info";
    }

    /**
     * 更新信息 -- POST
     * @return 更新成功与否
     */
    @ResponseBody
    @PostMapping("/updateInfo")
    public String updateInfo(String userName, String nickName, int age, String introduction, MultipartFile imgFile, HttpServletRequest req) {
        String avatar = FileUpLoadUtil.fileUpload(req, imgFile);
        HttpSession session = req.getSession();
        User oldUser = (User) session.getAttribute("_USER_MODEL");
        User user = new User();
        user.setId(oldUser.getId());
        user.setUserName(userName);
        user.setNickName(nickName);
        user.setAge(age);
        user.setIntroduction(introduction);
        user.setAvatar(avatar);
        int rowNum = userService.updateUser(user);
        User newUser = userService.getUserById(user.getId());
        session.setAttribute("_USER_IMG", newUser.getAvatar());
        session.setAttribute("_USER_MODEL", newUser);
        session.setAttribute("_USER_EMAIL", newUser.getEmail());
        return rowNum > 0 ? "{\"success\":true}" : "{\"success\":false, \"message\":\"未完成更新\"}";
    }

    /**
     * 跳转到”博客首页“
     * @return blog/index.jsp
     */
    @RequestMapping("/admin")
    public String jumpAdminJSP(HttpSession session, HttpServletRequest request) {
        // 获取登录用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        // 查询登录用户的博客近七天的浏览量
        List<DateAndView> list = blogViewsService.findViewsByUserId(loginUser.getId());
        list.sort(Comparator.comparing(DateAndView::getDate));
        request.setAttribute("list", list);
        return "admin";
    }

    /**
     * 跳转到修改密码的页面
     * @return pwd.jsp
     */
    @GetMapping("/updatePwd")
    public ModelAndView jumpToUpdatePwd(HttpSession session) {
        String email = (String) session.getAttribute("_USER_EMAIL");
        ModelAndView modelAndView = new ModelAndView("pwd");
        modelAndView.addObject("userEmail", email);
        return modelAndView;
    }

    /**
     * 修改密码
     * @return 修改信息
     */
    @ResponseBody
    @PostMapping("/updatePwd")
    public String updatePwd(String oldPwd, String newPwd, HttpSession session) {
        User user = (User) session.getAttribute("_USER_MODEL");
        if (!user.getPwd().equals(oldPwd)) {
            return "{\"success\":false, \"message\":\"密码错误\"}";
        }
        System.out.println("oldPwd = " + oldPwd);
        System.out.println("newPwd = " + newPwd);
        int rowNum = userService.updatePwd(user.getId(), newPwd);
        return rowNum > 0 ? "{\"success\":true}" : "{\"success\":false, \"message\":\"更新密码失败\"}";
    }

}
